﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using Flower.Workflow;
using AopAlliance.Intercept;
using Flower.Client;

namespace Flower.Processing.Advices
{
    internal class Logging : IMethodInterceptor
    {
        private readonly ILog _log;

        public Logging(ILog log)
        {
            _log = log;
        }

        public object Invoke(IMethodInvocation invocation)
        {
            var processor = invocation.Arguments[0] as Processor;
            if (processor == null)
            {
                return invocation.Proceed();
            }

            object interruption;

            var activity = (Activity)invocation.Target;
            _log.Trace
            (
                () => 
                    string.Format
                    (
                        "Executing activity {0} on processor {1}.", 
                        activity.Name,
                        processor.GetHashCode()
                    )
            );

            try
            {
                interruption = invocation.Proceed();

                if (interruption != null)
                {
                    _log.Trace(() => string.Format("Interruption {0}.", interruption));
                }
            }
            catch (Exception ex)
            {
                _log.Error
                (
                    string.Format
                    (
                        "Exception in activity {0}:\n{1}",
                        activity.Name,
                        ex
                    )
                );
                throw;
            }

            return interruption;
        }
    }
}
